package com.srwl.mytx.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.alibaba.fastjson.JSONObject;
import com.srwl.mytx.Constant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.dao.DBManager;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.Task;
import com.srwl.mytx.domain.Topic;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.OrderService;
import com.srwl.mytx.service.TaskService;
import com.srwl.mytx.service.TopicService;
import com.srwl.mytx.service.UserService;
import com.srwl.mytx.utils.DateUtils;
import com.srwl.mytx.utils.GlideLoadUtils;
import com.srwl.mytx.utils.Utils;
import com.srwl.mytx.widget.ConfirmDialog;
import com.srwl.mytx.widget.CountDownView;
import com.srwl.mytx.widget.TaskProgressView;

import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import me.dkzwm.widget.srl.MaterialSmoothRefreshLayout;
import me.dkzwm.widget.srl.SmoothRefreshLayout;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class TaskDetailActivity extends BaseActivity {
    private static final String TAG = "TaskDetailActivity";

    private static final int REQUEST_CODE_ORDER_SEND = 1;
    private LocalBroadcastManager broadcastManager;
    private BroadcastReceiver receiver;

    public static void startActivity(Activity activity, Task task, int requestCode) {
        activity.startActivityForResult(new Intent(activity, TaskDetailActivity.class).putExtra(Constant.EXTRA_INFO_TASK, task).putExtra("getTaskInfo", true), requestCode);
    }

    public static void startActivity(Context context, String taskId) {
        context.startActivity(new Intent(context, TaskDetailActivity.class).putExtra("taskId", taskId));
    }

    @BindView(R.id.progress_bar)
    ProgressBar progressBar;
    @BindView(R.id.tv_topic_title)
    TextView tv_topicTitle;
    @BindView(R.id.tv_amount)
    TextView tv_amount;
    @BindView(R.id.tv_task_id)
    TextView tv_taskId;

    @BindView(R.id.btn_commit)
    Button btn_commit;
    @BindView(R.id.btn_cancel)
    Button btn_cancel;
    @BindView(R.id.tv_status)
    TextView tv_orderStatus;

    @BindView(R.id.tv_tips)
    TextView tv_tips;
    @BindView(R.id.refresh_layout)
    MaterialSmoothRefreshLayout refreshLayout;
    @BindView(R.id.task_progress_view)
    TaskProgressView taskProgressView;
    @BindView(R.id.tv_amount_tips)
    TextView tvAmountTips;
    @BindView(R.id.tv_contact)
    TextView tv_contact;
    @BindView(R.id.count_down_view)
    CountDownView countDownView;
    @BindView(R.id.tv_created)
    TextView tv_created;
    @BindView(R.id.iv_topic_image)
    ImageView iv_topicImage;
    @BindView(R.id.tv_info_title)
    TextView tv_infoTitle;
    private Task task;
    private Topic topic;
    private boolean isEmployer;
    private User loginUserInfo;
    private boolean isSyncing;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_task_detail);
        ButterKnife.bind(this);
        task = getIntent().getParcelableExtra(Constant.EXTRA_INFO_TASK);
        String taskId = getIntent().getStringExtra("taskId");
        loginUserInfo = UserProfileManager.getInstance().getLoginUserInfo();

        if (task != null) {

            setViewAndEvent();
            boolean syncOrderData = getIntent().getBooleanExtra("getTaskInfo", false);
            //判断是否需要同步服务端的数据
            if (syncOrderData) {
                syncData(task.getId());
            }
        } else {
            if (taskId == null) {
                Log.e(TAG, "onCreate: taskId不能为空");
                return;
            }
            syncData(taskId);
        }

        intiBroadcast();
        initRefreshLayout();
    }

    private void setViewAndEvent() {
        isEmployer = loginUserInfo.getuId().equals(task.getEmployerId());
        if (isEmployer) {
            showEmployeeInfo(task.getuId());
        } else {
            topic = task.getTargetTopic();
            if (topic == null) {
                loadTopicData();
            } else {
                showTopicInfo();
            }
        }
        taskProgressView.setTaskStatus(task.getStatus(), isEmployer);
        tv_amount.setText(Utils.moneyFormat(task.getAmount()));
        tv_taskId.setText(task.getId());
        //自定义复制
//        tv_taskId.setOnLongClickListener(new View.OnLongClickListener() {
//            @Override
//            public boolean onLongClick(View v) {
//                tv_taskId.setBackgroundColor(getResources().getColor(R.color.btn_green_pressed));
//                View popView = getLayoutInflater().inflate(R.layout.clip_pop_layout, null);
//
//
//                final PopupWindow popupWindow = new PopupWindow(popView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
//                popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
//                popupWindow.showAsDropDown(tv_taskId, Utils.dpToPx(-10, TaskDetailActivity.this), Utils.dpToPx(-10, TaskDetailActivity.this), Gravity.END);
//                popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
//                    @Override
//                    public void onDismiss() {
//                        tv_taskId.setBackgroundColor(getResources().getColor(R.color.transparent));
//                    }
//                });
//                popView.findViewById(R.id.rl_clip).setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
//                        if (clipboard != null) {
//                            clipboard.setPrimaryClip(ClipData.newPlainText(null, task.getId()));
//                            popupWindow.dismiss();
//                            showToast("任务编号已经复制完成");
//                        }
//                    }
//                });
//                return false;
//            }
//        });
        tv_created.setText(DateUtils.dateToString(task.getCreated(), DateUtils.FORMAT_TIMESTAMP));
        tv_contact.setOnClickListener(v -> {
            if (isEmployer) {
                contact(task.getuId());
            } else {
                contact(task.getEmployerId());
            }
        });
        btn_commit.setVisibility(View.GONE);
        btn_cancel.setVisibility(View.GONE);
        countDownView.setVisibility(View.GONE);
        tv_tips.setVisibility(View.GONE);
        switch (task.getStatus()) {
            case Constant.TASK_STATUS_INIT:
                showCancelButton();
                if (isEmployer) {
                    btn_commit.setText("确认任务");
                    btn_commit.setVisibility(View.VISIBLE);
                    btn_commit.setOnClickListener(v -> confirmTask());
                    tv_orderStatus.setText("等待确认");
                } else {
                    tv_orderStatus.setText("任务确认中...");
                }
                tv_tips.setVisibility(View.VISIBLE);
                tv_tips.setText("任务确认后是双方合作的开始");
                break;

            case Constant.TASK_STATUS_CONFIRM_FAIL:
                if (isEmployer) {
                    tv_orderStatus.setText("任务已取消");
                    tv_tips.setText("主动取消");
                } else {
                    tv_orderStatus.setText("未通过确认");
                    tv_tips.setText("任务未获得对方确认");
                }
                tv_tips.setVisibility(View.VISIBLE);
                break;
            case Constant.TASK_STATUS_CONFIRM:
                if (isEmployer) {
                    showCancelButton();
                    tv_orderStatus.setText("任务已确认");
                    tv_tips.setText("等待对方完成");
                } else {
                    tv_orderStatus.setText("任务已确认");
                    tv_tips.setText("尽快完成吧");

                    showFinishTaskButton();
                    showCancelButtonWithDialog();
                }
                tv_tips.setVisibility(View.VISIBLE);
                break;
            case Constant.TASK_STATUS_EMPLOYER_CANCEL:
                showExpireLayout("秒自动取消");
                if (isEmployer) {
                    tv_orderStatus.setText("取消任务中...");
                    // tv_tips.setText("到期没处理，将自动取消");
                } else {
                    tv_orderStatus.setText("对方请求取消任务");
                    // tv_tips.setText("到期没处理，将自动取消");
                    showRefuseCancelButton();
                    showAgreeCancelButton();
                }
                break;

            case Constant.TASK_STATUS_EXPIRY_AUTO_CANCEL:

                tv_orderStatus.setText("到期没处理，已经自动取消");
                break;
            case Constant.TASK_STATUS_EMPLOYEE_CANCEL:
                if (isEmployer) {
                    tv_orderStatus.setText("任务已取消");
                    tv_tips.setText("对方取消");
                } else {
                    tv_orderStatus.setText("任务已取消");
                    tv_tips.setText("主动取消");
                }
                tv_tips.setVisibility(View.VISIBLE);
                break;
            case Constant.TASK_STATUS_EMPLOYEE_REFUSE_CANCEL:
                if (isEmployer) {
                    tv_orderStatus.setText("对方拒绝取消任务");
                    tv_tips.setText("可以再次发起取消任务");
                    tv_tips.setVisibility(View.VISIBLE);
                    showCancelButton();
                } else {//对于被雇佣者来说，拒绝了雇主的取消任务请求后，任务回归正常状态
                    tv_orderStatus.setText("任务进行中...");
                    showFinishTaskButton();
                    showCancelButtonWithDialog();
                }

                break;
            case Constant.TASK_STATUS_EMPLOYEE_AGREE_CANCEL:
                if (isEmployer) {
                    tv_orderStatus.setText("任务已取消");
                    tv_tips.setText("主动取消");
                } else {
                    tv_orderStatus.setText("任务已取消");
                    tv_tips.setText("对方取消");
                }
                tv_tips.setVisibility(View.VISIBLE);
                break;
            case Constant.TASK_STATUS_APPLY_FINISH_TASK:
                taskProgressView.setVisibility(View.VISIBLE);
                if (isEmployer) {
                    tv_orderStatus.setText("等待任务验收");
                    showFinishFailButton();
                    showAgreeApplyButton();
                } else {
                    tv_orderStatus.setText("任务验收中...");
                }
                showExpireLayout("秒自动结算");
                // tv_tips.setVisibility(View.VISIBLE);
                // tv_tips.setText("到期未处理，任务将自动完成并结算");
                break;
            case Constant.TASK_STATUS_EMPLOYER_REFUSE_FINISH_APPLY:
                if (isEmployer) {
                    tv_orderStatus.setText("任务验收未通过");
                    showCancelButton();
                } else {
                    tv_orderStatus.setText("任务验收未通过");
                    tv_tips.setText("可以重新发起任务验收");
                    tv_tips.setVisibility(View.VISIBLE);
                    showFinishTaskButton();
                    showCancelButtonWithDialog();
                }

                break;

            case Constant.TASK_STATUS_CHECK_SUCCESS:
                if (isEmployer) {
                    tv_orderStatus.setText("任务已结算");
                    tvAmountTips.setText("赏金已转账至对方的账户余额");
                } else {
                    tv_orderStatus.setText("任务已结算");
                    tvAmountTips.setText("赏金已到账至您的账户余额");
                }
                break;
            case Constant.TASK_STATUS_EXPIRY_AUTO_FINISH:

                if (isEmployer) {
                    tv_orderStatus.setText("已自动结算");
                    tvAmountTips.setText("赏金已转账至对方的账户余额");
                } else {
                    tv_orderStatus.setText("已自动结算");
                    tvAmountTips.setText("赏金已到账至您的账户余额");
                }

                break;
            case Constant.TASK_STATUS_OTHER_ONE_COMPLETE:
                if (isEmployer) {
                    tv_orderStatus.setText("任务已终止");
                    tv_tips.setText("该悬赏已经有其他人完成任务了");
                } else {
                    tv_orderStatus.setText("任务已终止");
                    tv_tips.setText("该悬赏已经有其他人完成了");
                }
                tv_tips.setVisibility(View.VISIBLE);
                break;

        }

    }

    private void initRefreshLayout() {
        refreshLayout.setDisableRefresh(false);
        refreshLayout.setDisableLoadMore(true);
        refreshLayout.setEnableOverScroll(false);
        refreshLayout.setOnRefreshListener(new SmoothRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefreshing() {
                syncData(task.getId());
            }

            @Override
            public void onLoadingMore() {

            }
        });
    }


    private void showCancelDialog() {
        ConfirmDialog dialog = new ConfirmDialog(this, "提醒", "取消后，整个任务进入结束状态，无法再重启，务必谨慎操作", "确定取消", "暂不取消", true);
        dialog.setConfirmListener(new ConfirmDialog.ConfirmListener() {
            @Override
            public void confirm() {
                cancelTask();

            }
        });
        dialog.show();
    }

    private void showCancelDialog_v1() {
        ConfirmDialog dialog = new ConfirmDialog(this, "提示", "确定取消该任务？", true);
        dialog.setConfirmListener(new ConfirmDialog.ConfirmListener() {
            @Override
            public void confirm() {
                cancelTask();

            }
        });
        dialog.show();
    }

    private void showAgreeApplyButton() {
        btn_commit.setText("任务已完成");
        btn_commit.setVisibility(View.VISIBLE);
        btn_commit.setOnClickListener(v -> showConfirmDialog());
    }

    private void showConfirmDialog() {
        ConfirmDialog dialog = new ConfirmDialog(this, "提醒", "确保任务已经完成，确定后会进行赏金结算，不可撤销", true);
        dialog.setConfirmListener(this::confirmTaskFinish);
        dialog.show();
    }


    private void showFinishFailButton() {
        btn_cancel.setText("任务未完成");
        btn_cancel.setVisibility(View.VISIBLE);
        btn_cancel.setOnClickListener(v -> refuseApplyFinish());
    }

    /**
     * @param secondEndTips 倒计时秒后面的提示
     */
    private void showExpireLayout(String secondEndTips) {
        Date expiryDate = task.getExpiryDate();
        if (expiryDate == null) {
            return;
        }
//        rl_expiryTime.setVisibility(View.VISIBLE);
//        tv_expiryTime.setText(DateUtils.dateToString(expiryDate, "yyyy-MM-dd HH:mm"));
        countDownView.clear();
        countDownView.setVisibility(View.VISIBLE);
        countDownView.init(secondEndTips, expiryDate, new CountDownView.InteractionListener() {

            @Override
            public void onCountDownStop() {

            }
        });


    }

    private void showFinishTaskButton() {
        btn_commit.setVisibility(View.VISIBLE);
        btn_commit.setText("完成任务");
        btn_commit.setOnClickListener(v -> applyFinishTask());
    }

    private void showAgreeCancelButton() {
        btn_commit.setVisibility(View.VISIBLE);
        btn_commit.setText("同意取消");
        btn_commit.setOnClickListener(v -> agreeCancel());

    }

    private void confirmTaskFinish() {
        progressBar.setVisibility(View.VISIBLE);
        RetrofitManager.getInstance().createRequest(TaskService.class)
                .confirmTaskFinish(task.getId())
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressBar.setVisibility(View.GONE);
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            showToast(getString(R.string.system_busy));
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());

                            switch (result.getStatus()) {
                                case Constant.REWARD_TASK_INVALID:
                                    showToast("任务已经失效或者过期");
                                    setViewAndEvent();
                                    setResult(RESULT_OK, new Intent().putExtra(Constant.EXTRA_INFO_TASK, task));
                                    break;
                                case Constant.REWARD_TASK_STATUS_ERROR:
                                    showToast("任务状态有误");
                                    syncData(task.getId());
                                    break;
                                case Constant.TOPIC_STATUS_ERROR:
                                    task.setStatus(Constant.TASK_STATUS_OTHER_ONE_COMPLETE);
                                    Object expireDateObject = result.getData();
                                    if (expireDateObject != null) {
                                        Date expireDate = new Date((long) expireDateObject);
                                        task.setExpiryDate(expireDate);
                                    }
                                    setViewAndEvent();
                                    showToast("悬赏任务已经结束了");
                                    setResult(RESULT_OK, new Intent().putExtra(Constant.EXTRA_INFO_TASK, task));
                                    break;

                                default:
                                    showToast(getString(R.string.system_busy));
                            }
                            return;
                        }
                        Log.d(TAG, "onResponse: 任务验收完成");
                        Object data = result.getData();
                        if (data != null) {
                            JSONObject userObject = (JSONObject) data;
                            User user = userObject.toJavaObject(User.class);
                            UserProfileManager.getInstance().syncLoginUserInfo(user);
                        }
                        task.setStatus(Constant.TASK_STATUS_CHECK_SUCCESS);
                        taskProgressView.setTaskStatus(task.getStatus(), isEmployer);
                        setViewAndEvent();
                        showToast("任务验收完成");
                        setResult(RESULT_OK, new Intent().putExtra(Constant.EXTRA_INFO_TASK, task));
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        progressBar.setVisibility(View.GONE);
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        showToast(getString(R.string.system_busy));
                    }
                });
    }


    /**
     * 任务未完成，验收未通过 完成申请 被拒绝
     */
    private void refuseApplyFinish() {
        progressBar.setVisibility(View.VISIBLE);
        RetrofitManager.getInstance().createRequest(TaskService.class)
                .refuseApplyFinish(task.getId())
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressBar.setVisibility(View.GONE);
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            showToast(getString(R.string.system_busy));
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());

                            switch (result.getStatus()) {
                                case Constant.REWARD_TASK_INVALID:
                                    showToast("任务已经失效或者过期");
                                    break;

                                default:
                                    showToast(getString(R.string.system_busy));
                            }
                            return;
                        }
                        Log.d(TAG, "onResponse: 拒绝申请完成");
                        task.setStatus(Constant.TASK_STATUS_EMPLOYER_REFUSE_FINISH_APPLY);
                        taskProgressView.setTaskStatus(task.getStatus(), isEmployer);
                        setViewAndEvent();
                        showToast("拒绝了对方的任务完成验收申请");
                        setResult(RESULT_OK, new Intent().putExtra(Constant.EXTRA_INFO_TASK, task));
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        progressBar.setVisibility(View.GONE);
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        showToast(getString(R.string.system_busy));
                    }
                });
    }


    private void agreeCancel() {

        progressBar.setVisibility(View.VISIBLE);
        RetrofitManager.getInstance().createRequest(TaskService.class)
                .agreeCancelTask(task.getId())
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressBar.setVisibility(View.GONE);
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            showToast(getString(R.string.system_busy));
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());

                            switch (result.getStatus()) {
                                case Constant.REWARD_TASK_INVALID:
                                    showToast("任务已经失效或者过期");
                                    break;
                                case Constant.REWARD_TASK_STATUS_ERROR:
                                    showToast("任务状态有误");
                                    syncData(task.getId());
                                    break;
                                default:
                                    showToast(getString(R.string.system_busy));
                            }
                            return;
                        }
                        Log.d(TAG, "onResponse: 同意取消任务完成");
                        task.setStatus(Constant.TASK_STATUS_EMPLOYEE_AGREE_CANCEL);
                        taskProgressView.setTaskStatus(task.getStatus(), isEmployer);
                        setViewAndEvent();
                        showToast("悬赏任务已经取消");
                        setResult(RESULT_OK, new Intent().putExtra(Constant.EXTRA_INFO_TASK, task));
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        progressBar.setVisibility(View.GONE);
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        showToast(getString(R.string.system_busy));
                    }
                });
    }

    //显示拒绝取消按键
    private void showRefuseCancelButton() {
        btn_cancel.setText("拒绝取消");
        btn_cancel.setVisibility(View.VISIBLE);
        btn_cancel.setOnClickListener(v -> refuseCancelTask());
    }

    private void refuseCancelTask() {
        progressBar.setVisibility(View.VISIBLE);
        RetrofitManager.getInstance().createRequest(TaskService.class)
                .refuseCancelTask(task.getId())
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressBar.setVisibility(View.GONE);
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            showToast(getString(R.string.system_busy));
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());

                            switch (result.getStatus()) {
                                case Constant.REWARD_TASK_INVALID:
                                    showToast("任务已经失效或者过期");
                                    break;
                                case Constant.REWARD_TASK_STATUS_ERROR:
                                    showToast("任务状态有误");
                                    syncData(task.getId());
                                    break;
                                default:
                                    showToast(getString(R.string.system_busy));
                            }
                            return;
                        }
                        Log.d(TAG, "onResponse: 拒绝完成");
                        task.setStatus(Constant.TASK_STATUS_EMPLOYEE_REFUSE_CANCEL);
                        taskProgressView.setTaskStatus(task.getStatus(), isEmployer);
                        setViewAndEvent();
                        showToast("拒绝完成");
                        setResult(RESULT_OK, new Intent().putExtra(Constant.EXTRA_INFO_TASK, task));
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        progressBar.setVisibility(View.GONE);
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        showToast(getString(R.string.system_busy));
                    }
                });

    }

    private void showCancelButton() {
        btn_cancel.setText("取消任务");
        btn_cancel.setVisibility(View.VISIBLE);
        btn_cancel.setOnClickListener(v -> showCancelDialog_v1());
    }

    private void showCancelButtonWithDialog() {
        btn_cancel.setText("取消任务");
        btn_cancel.setVisibility(View.VISIBLE);
        btn_cancel.setOnClickListener(v -> showCancelDialog());
    }

    private void cancelTask() {
        progressBar.setVisibility(View.VISIBLE);
        RetrofitManager.getInstance().createRequest(TaskService.class)
                .cancelTask(task.getId())
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressBar.setVisibility(View.GONE);
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            showToast(getString(R.string.system_busy));
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());

                            switch (result.getStatus()) {
                                case Constant.REWARD_TASK_INVALID:
                                    showToast("任务已经失效或者过期");
                                    break;
                                case Constant.REWARD_TASK_STATUS_ERROR:
                                    showToast("任务状态有误");
                                    syncData(task.getId());
                                    break;
                                default:
                                    showToast(getString(R.string.system_busy));
                            }
                            return;
                        }
                        Log.d(TAG, "onResponse: 任务已经取消");
                        if (isEmployer) {
                            if (task.getStatus() == Constant.TASK_STATUS_INIT) {  //没有确认就取消
                                task.setStatus(Constant.TASK_STATUS_CONFIRM_FAIL);
                            } else {//确认后取消
                                task.setStatus(Constant.TASK_STATUS_EMPLOYER_CANCEL);
                                Object expireDateObject = result.getData();
                                if (expireDateObject != null) {
                                    Date expireDate = new Date((long) expireDateObject);
                                    task.setExpiryDate(expireDate);
                                }
                            }
                        } else {
                            task.setStatus(Constant.TASK_STATUS_EMPLOYEE_CANCEL);
                        }
                        taskProgressView.setTaskStatus(task.getStatus(), isEmployer);
                        setViewAndEvent();
                        showToast("任务已经取消");
                        setResult(RESULT_OK, new Intent().putExtra(Constant.EXTRA_INFO_TASK, task));
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        progressBar.setVisibility(View.GONE);
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        showToast(getString(R.string.system_busy));
                    }
                });


    }


    /**
     * 申请任务验收
     */
    private void applyFinishTask() {
        progressBar.setVisibility(View.VISIBLE);
        RetrofitManager.getInstance().createRequest(TaskService.class)
                .applyFinishTask(task.getId())
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressBar.setVisibility(View.GONE);
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            showToast(getString(R.string.system_busy));
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());

                            switch (result.getStatus()) {
                                case Constant.REWARD_TASK_INVALID:
                                    showToast("任务已经失效或者过期");
                                    setViewAndEvent();
                                    setResult(RESULT_OK, new Intent().putExtra(Constant.EXTRA_INFO_TASK, task));
                                    break;
                                case Constant.TOPIC_STATUS_ERROR:
                                    syncData(task.getId());
                                    showToast("任务状态有误");
                                    setResult(RESULT_OK, new Intent().putExtra(Constant.EXTRA_INFO_TASK, task));
                                    break;
                                default:
                                    showToast(getString(R.string.system_busy));
                            }
                            return;
                        }
                        Log.d(TAG, "onResponse: 申请任务验收完成");
                        task.setStatus(Constant.TASK_STATUS_APPLY_FINISH_TASK);
                        Object expireDateObject = result.getData();
                        if (expireDateObject != null) {
                            Date expireDate = new Date((long) expireDateObject);
                            task.setExpiryDate(expireDate);
                        }
                        taskProgressView.setTaskStatus(task.getStatus(), isEmployer);
                        setViewAndEvent();
                        showToast("任务验收已经提交，等待对方确认");
                        setResult(RESULT_OK, new Intent().putExtra(Constant.EXTRA_INFO_TASK, task));
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        progressBar.setVisibility(View.GONE);
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        showToast(getString(R.string.system_busy));
                    }
                });


    }

    /**
     * 任务确认
     */
    private void confirmTask() {

        RetrofitManager.getInstance().createRequest(TaskService.class)
                .confirmTask(task.getId())
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressBar.setVisibility(View.GONE);
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            showToast(getString(R.string.system_busy));
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());

                            switch (result.getStatus()) {
                                case Constant.REWARD_TASK_INVALID:
                                    showToast("任务已经失效或者过期");
                                    // setViewAndEvent();
                                    // setResult(RESULT_OK, new Intent().putExtra(Constant.EXTRA_INFO_TASK, task));
                                    break;
                                case Constant.TOPIC_STATUS_ERROR:
                                    showToast(result.getMsg());
                                    break;
                                default:
                                    showToast(getString(R.string.system_busy));
                            }

                            return;
                        }
                        Log.d(TAG, "onResponse: 任务已经确认");
                        task.setStatus(Constant.TASK_STATUS_CONFIRM);
                        setViewAndEvent();
                        showToast("任务已经确认");
                        setResult(RESULT_OK, new Intent().putExtra(Constant.EXTRA_INFO_TASK, task));
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        progressBar.setVisibility(View.GONE);
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        showToast(getString(R.string.system_busy));
                    }
                });


    }


    /**
     * 同意退款
     */
    private void agreeRefund() {

        progressBar.setVisibility(View.VISIBLE);
        RetrofitManager.getInstance().createRequest(OrderService.class)
                .agreeRefund(task)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressBar.setVisibility(View.GONE);
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            showToast(getString(R.string.system_busy));
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            showToast(getString(R.string.system_busy));
                            return;
                        }
                        showToast(btn_cancel, "同意退款完成");
                        task.setStatus(Constant.ORDER_STATUS_REFUND_COMPLETED);
                        setResult(RESULT_OK, new Intent().putExtra(Constant.EXTRA_INFO_TASK, task));
                        setViewAndEvent();


                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        progressBar.setVisibility(View.GONE);
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        showToast(getString(R.string.system_busy));
                    }
                });
    }

    private void toTopicDetail() {
        if (topic != null) {
            TopicDetailsActivity.startActivity(this, topic);
        } else {
            getFullTopic(task.gettId());
        }
    }

    private void getFullTopic(String topicId) {
        progressBar.setVisibility(View.VISIBLE);
        RetrofitManager.getInstance().createRequest(TopicService.class)
                .get(topicId)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressBar.setVisibility(View.INVISIBLE);
                        CommonResult body = response.body();
                        if (!response.isSuccessful() || body == null) {
                            return;
                        }
                        if (body.isError()) {
                            return;
                        }
                        Log.d(TAG, "onResponse: 获取完成topic 完成");
                        JSONObject object = (JSONObject) body.getData();
                        if (object == null) {
                            return;
                        }
                        topic = object.toJavaObject(Topic.class);
                        TopicDetailsActivity.startActivity(TaskDetailActivity.this, topic);
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        progressBar.setVisibility(View.INVISIBLE);
                        Log.e(TAG, "onFailure: " + t.getMessage());
                    }
                });


    }


    private void syncData(String taskId) {
        if (!Helper.getInstance().isNetworkConnected()) {
            if (refreshLayout != null) refreshLayout.refreshComplete();
            showToast_v1(getString(R.string.network_anomalies));
            return;
        }
        if (isSyncing) {
            return;
        }
        isSyncing = true;
        RetrofitManager.getInstance().createRequest(TaskService.class)
                .getTaskInfo(taskId)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        isSyncing = false;
                        refreshLayout.refreshComplete();
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            return;
                        }


                        Log.d(TAG, "onResponse: 同步信息完成");
                        JSONObject body = (JSONObject) result.getData();
                        if (body == null) {
                            return;
                        }
                        task = body.toJavaObject(Task.class);
                        setResult(RESULT_OK, new Intent().putExtra(Constant.EXTRA_INFO_TASK, task));
                        setViewAndEvent();

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        isSyncing = false;
                        refreshLayout.refreshComplete();
                        Log.e(TAG, "onFailure: " + t.getMessage());
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }

    }

    private void contact(String targetUserId) {
        User userInfo = Helper.getInstance().queryUserInfoById(targetUserId);
        if (userInfo != null) {
            ChatActivity.startActivity(TaskDetailActivity.this, userInfo);
        } else {
            getFullUserInfo(targetUserId, false);
        }
    }


    private void getFullUserInfo(String userId, boolean showUserInfo) {

        RetrofitManager.getInstance().createRequest(UserService.class)
                .getUserInfo(userId)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            // showToast(tv_customerService, getString(R.string.system_busy));
                            return;
                        }
                        JSONObject object = (JSONObject) result.getData();
                        //把用户作为临时联系人 保存在数据库
                        User userInfo = object.toJavaObject(User.class);
                        if (userInfo == null) {
                            return;
                        }
                        userInfo.setType(Constant.USER_TYPE_TEMP);
                        DBManager.getInstance().getDaoSession().getUserDao().insertOrReplace(userInfo);
                        if (showUserInfo) {
                            // Glide.with(TaskDetailActivity.this).load(userInfo.getAvatar()).error(R.drawable.tx_default_place).diskCacheStrategy(DiskCacheStrategy.ALL).into(iv_topicImage);
                            GlideLoadUtils.glideLoad(TaskDetailActivity.this, userInfo.getAvatar(), iv_topicImage, R.drawable.tx_default_avatar_1);
                            tv_topicTitle.setText(userInfo.getUsername() == null ? userInfo.getNick() : userInfo.getUsername());
                        } else {
                            ChatActivity.startActivity(TaskDetailActivity.this, userInfo);
                        }

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        // showToast(tv_customerService, getString(R.string.system_busy));
                    }
                });


    }


    private void loadTopicData() {

        RetrofitManager.getInstance().createRequest(TopicService.class)
                .getTopicFromMysql_v3(task.gettId())
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            // showToast(getString(R.string.system_busy));
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            // showToast(getString(R.string.system_busy));
                        }
                        CommonResult body = response.body();
                        JSONObject data = (JSONObject) body.getData();
                        if (data == null) {
                            return;
                        }
                        topic = data.toJavaObject(Topic.class);

                        showTopicInfo();
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        t.printStackTrace();
                    }
                });
    }

    private void showTopicInfo() {
        if (topic == null) {
            return;
        }
        String iconUrl = Utils.getIconUrlScale20(topic);
        // Glide.with(TaskDetailActivity.this).load(iconUrl).error(R.drawable.tx_default_place).diskCacheStrategy(DiskCacheStrategy.ALL).into(iv_topicImage);
        GlideLoadUtils.glideLoad(TaskDetailActivity.this, iconUrl, iv_topicImage, R.drawable.tx_default_place);
        iv_topicImage.setOnClickListener(v -> toTopicDetail());
        tv_topicTitle.setText(topic.getTitle());
        tv_topicTitle.setOnClickListener(v -> toTopicDetail());
    }


    private void showEmployeeInfo(String targetUserId) {
        tv_infoTitle.setText("任务领取者信息");
        User userInfo = Helper.getInstance().queryUserInfoById(targetUserId);
        if (userInfo != null) {
            //Glide.with(TaskDetailActivity.this).load(userInfo.getAvatar()).error(R.drawable.tx_default_place).diskCacheStrategy(DiskCacheStrategy.ALL).into(iv_topicImage);
            GlideLoadUtils.glideLoad(TaskDetailActivity.this, userInfo.getAvatar(), iv_topicImage, R.drawable.tx_default_avatar_1);

            tv_topicTitle.setText(userInfo.getUsername() == null ? userInfo.getNick() : userInfo.getUsername());
        } else {
            getFullUserInfo(targetUserId, true);
        }
        iv_topicImage.setOnClickListener(v -> showUserProfile(userInfo));
        tv_topicTitle.setOnClickListener(v -> showUserProfile(userInfo));
    }

    private void showUserProfile(User userInfo) {
        if (userInfo == null) {
            return;
        }
        UserProfileActivity.startActivity(TaskDetailActivity.this, userInfo);
    }


    private void intiBroadcast() {
        broadcastManager = LocalBroadcastManager.getInstance(this);
        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Task pushTask = intent.getParcelableExtra(Constant.EXTRA_INFO_TASK);
                if (pushTask != null && TextUtils.equals(pushTask.getId(), task.getId())) {
                    task = pushTask;
                    setViewAndEvent();
                    TaskDetailActivity.this.setResult(RESULT_OK, intent);
                }
            }
        };
        IntentFilter filter = new IntentFilter();
        filter.addAction(Constant.ACTION_RECEIVED_TASK_MESSAGE);
        broadcastManager.registerReceiver(receiver, filter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        countDownView.clear();
        if (broadcastManager != null) {
            broadcastManager.unregisterReceiver(receiver);
        }
    }
}
